<?php
namespace Admin\Controller;

class UploadController extends AdminController {

    public function file()
    {
        $config_url = THINK_PATH.'../Public/static/ueditor/php/config.json';
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($config_url)), true);
        $action = I('request.action');
        switch ($action) {
            case 'config':
                $result =  json_encode($CONFIG);
                break;
            /* 上传图片 */
            case 'uploadimage':
            /* 上传文件 */
            case 'uploadfile':
                $result = $this->_upload();
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }

    private function _upload()
    {
        $Picture = D('Api/Picture');
        $picDriver = C('PICTURE_UPLOAD_DRIVER');
        \Think\Log::record("[DEBUG] -- [UPLOAD] -- CONFIG: ". json_encode($picDriver), 'DEBUG');
        $data = $Picture->upload(
            $_FILES,
            C('PICTURE_UPLOAD'),
            C('PICTURE_UPLOAD_DRIVER'),
            C("UPLOAD_{$picDriver}_CONFIG")
        );
        $info = $data['upfile'];

        // {
        //     "state":"SUCCESS",
        //     "url":"/ueditor/php/upload/image/20160803/1470224030931728.jpg",
        //     "title":"1470224030931728.jpg",
        //     "original":"2.jpg",
        //     "type":".jpg",
        //     "size":71570
        // }
        uri_format($info['path']);
        $res = [
            'state' => 'SUCCESS',
            'url' => $info['path'],
            'title' => $info['savename'],
            'original' => $info['name'],
            'type' => '.'.$info['ext'],
            'size' => $info['size']
        ];
        return json_encode($res);
    }
}